home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / snip1292.zip / LTOSTR.C < prev    next >
C/C++ Source or Header  |  1992-12-26  |  2KB  |  58 lines

  1. /*
  2. **  LTOSTR.C -- routine and example program to convert a long int to
  3. **  the specified numeric base, from 2 to 36.
  4. **
  5. **  Written by Thad Smith III, Boulder, CO. USA  9/06/91 
  6. **  and contributed to the Public Domain.
  7. */
  8.  
  9. #include <stdlib.h>
  10.  
  11. char *                  /* addr of terminating null */
  12. ltostr (
  13.     char *str,          /* output string */
  14.     long val,           /* value to be converted */
  15.     unsigned base)      /* conversion base       */
  16. {
  17.     ldiv_t r;           /* result of val / base */
  18.  
  19.     if (base > 36)      /* no conversion if wrong base */
  20.     {
  21.         str = '\0';
  22.         return str;
  23.     }
  24.     if (val < 0)    *str++ = '-';
  25.     r = ldiv (labs(val), base);
  26.  
  27.     /* output digits of val/base first */
  28.  
  29.     if (r.quot > 0)  str = ltostr (str, r.quot, base);
  30.  
  31.     /* output last digit */
  32.  
  33.     *str++ = "0123456789abcdefghijklmnopqrstuvwxyz"[(int)r.rem];
  34.     *str   = '\0';
  35.     return str;
  36. }
  37.  
  38. #include <stdio.h>
  39. main()
  40. {
  41.     char buf[100], line[100], *tail;
  42.     long v;
  43.     int inbase, outbase;
  44.  
  45.     for (;;)
  46.     {
  47.         printf ("inbase, value, outbase? ");
  48.         fgets (line, sizeof line, stdin);
  49.         sscanf (line, " %d%*[, ]%[^, ]%*[, ]%d", &inbase, buf, &outbase);
  50.         if (inbase == 0)
  51.             break;                              /* exit if first number 0 */
  52.         v = strtol (buf, &tail, inbase);
  53.         ltostr (buf, v, outbase);
  54.         printf ("=%ld (10) = %s (%d).\n", v, buf, outbase);
  55.     };
  56.     return 0;
  57. }
  58.